interface Cookie {
  setCookie<T>(arg: { key: string; value: T; exdays?: number, path?: string }): void;
  /**
   * 得到cookie值
   * @param key - cookie的属性值key
   * @returns 对应属性的value
   */
  getCookie(key: string): any;
  /**
   * 删除cookie值
   * @param key - 属性
   */
  deleteCookie(key: string): void;
}

const Cookie: Cookie = {
  setCookie<T>(arg: { key: string; value: T; exdays?: number, path?: string }): void {
    //设置cookie，用户保存当前用户的登录信息
    const date: Date = new Date();
    date.setTime(date.getTime() + ((arg.exdays ? arg.exdays : 1) * 24 * 60 * 60 * 1000));
    const expires = "expires=" + date.toUTCString();//设置cookie保存期限
    document.cookie = `${arg.key}=${JSON.stringify(arg.value)};${expires};path=${arg.path ? arg.path : '/'};`;
  },

  getCookie(key: string): any {
    let data: any = '';
    const cookies: Array<string> = document.cookie.split(";");
    for (const item of cookies) {
      if (item.trim().startsWith(key)) {
        const value: string = item.trim().slice(key.length + 1);
        if (value.length) {
          const parseObj = JSON.parse(value);
          data = parseObj;
        }
        break;
      }
    }

    return data
  },

  deleteCookie(key: string): void {
    //删除cookie
    document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
  },
}

export default Cookie